package com.xxl.job.admin.service;

import com.wisdom.wisdomhub.api.JwtSessionInfo;
import com.wisdom.wisdomhub.opeanapi.api.session.SessionApiRestTemplate;
import com.wisdom.wisdomhub.openapi.session.param.OpenUserLogin;
import com.xxl.job.admin.core.model.XxlJobUser;
import com.xxl.job.admin.core.util.CookieUtil;
import com.xxl.job.admin.core.util.I18nUtil;
import com.xxl.job.admin.core.util.JacksonUtil;
import com.xxl.job.admin.dao.XxlJobUserDao;
import com.xxl.job.admin.wisdom.WisdomRemoteUtil;
import com.xxl.job.core.biz.model.ReturnT;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigInteger;
import java.util.Objects;

/**
 * @author xuxueli 2019-05-04 22:13:264
 */
@Configuration
public class LoginService {

    public static final String LOGIN_IDENTITY_KEY = "XXL_JOB_LOGIN_IDENTITY";

    @Resource
    private XxlJobUserDao xxlJobUserDao;

    @Resource
    private WisdomRemoteUtil wisdomRemoteUtil;


    private String makeToken(XxlJobUser xxlJobUser) {
        String tokenJson = JacksonUtil.writeValueAsString(xxlJobUser);
        String tokenHex = new BigInteger(tokenJson.getBytes()).toString(16);
        return tokenHex;
    }

    private XxlJobUser parseToken(String tokenHex) {
        XxlJobUser xxlJobUser = null;
        if (tokenHex != null) {
            String tokenJson = new String(new BigInteger(tokenHex, 16).toByteArray());      // username_password(md5)
            xxlJobUser = JacksonUtil.readValue(tokenJson, XxlJobUser.class);
        }
        return xxlJobUser;
    }


    public ReturnT<String> login(HttpServletRequest request, HttpServletResponse response, String username, String password, boolean ifRemember) {

        // param
        if (username == null || username.trim().length() == 0 || password == null || password.trim().length() == 0) {
            return new ReturnT<String>(500, I18nUtil.getString("login_param_empty"));
        }

        // valid passowrd
        XxlJobUser xxlJobUser = xxlJobUserDao.loadByUserName(username);
        String loginToken;
        try {
            OpenUserLogin login = new OpenUserLogin();
            login.setUsername(username);
            login.setPassword(password);
            JwtSessionInfo sessionInfo = wisdomRemoteUtil.login(login);
            if (xxlJobUser == null) {
                xxlJobUser = new XxlJobUser();
                xxlJobUser.setRole(1);
                xxlJobUser.setUsername(sessionInfo.getAccount());
                xxlJobUser.setPermission("-1");
                xxlJobUser.setPassword("-1");
                xxlJobUserDao.save(xxlJobUser);
            }
            loginToken = wisdomRemoteUtil.makeToken(sessionInfo);
        }catch (Exception e){
            return new ReturnT<String>(500, I18nUtil.getString("login_param_unvalid"));
        }
        if (xxlJobUser == null) {
            return new ReturnT<String>(500, I18nUtil.getString("login_param_unvalid"));
        }
        if (StringUtils.isBlank(loginToken)){
            return new ReturnT<String>(500, I18nUtil.getString("login_param_unvalid"));
        }

        // do login
        CookieUtil.set(response, LOGIN_IDENTITY_KEY, loginToken, ifRemember);
        return ReturnT.SUCCESS;
    }

    /**
     * logout
     *
     * @param request
     * @param response
     */
    public ReturnT<String> logout(HttpServletRequest request, HttpServletResponse response) {
        CookieUtil.remove(request, response, LOGIN_IDENTITY_KEY);
        return ReturnT.SUCCESS;
    }

    /**
     * 检查是否登陆
     *
     * @param request
     * @return
     */
    public XxlJobUser ifLogin(HttpServletRequest request, HttpServletResponse response) {
        SessionApiRestTemplate sessionApiRestTemplate = wisdomRemoteUtil.getSessionApiRestTemplate();
        String cookieToken = wisdomRemoteUtil.getToken();
        if (StringUtils.isBlank(cookieToken)) {
            cookieToken = CookieUtil.getValue(request, LOGIN_IDENTITY_KEY);
        } else {
            JwtSessionInfo jwtSessionInfo = sessionApiRestTemplate.validToken(cookieToken);
            cookieToken = wisdomRemoteUtil.makeToken(jwtSessionInfo);
            // do login
            CookieUtil.set(response, LOGIN_IDENTITY_KEY, cookieToken, false);
        }
        if (cookieToken != null) {
            JwtSessionInfo cookieUser = null;
            try {
                cookieUser = wisdomRemoteUtil.parseToken(cookieToken);
            } catch (Exception e) {
                logout(request, response);
            }
            if (cookieUser != null) {
                XxlJobUser dbUser = new XxlJobUser();
                dbUser.setRole(1);
                dbUser.setUsername(cookieUser.getAccount());
                dbUser.setPermission("-1");
                dbUser.setPassword("-1");
                XxlJobUser xxlJobUser = xxlJobUserDao.loadByUserName(cookieUser.getAccount());
                if (Objects.isNull(xxlJobUser)) {
                    xxlJobUserDao.save(dbUser);
                }
                return dbUser;
            }
        }
        return null;
    }


}
